//
//  UIImage+utils.m
//  helper
//
//  Created by huangyi on 12-10-29.
//  Copyright (c) 2012年 huangyi. All rights reserved.
//

#import "UIImage+utils.h"
#import "NSObject+math.h"
#import "NSString+path.h"
#import "NSString+urlstring.h"
#import "UIView+utils.h"

static int rgba8FromImage(UIImage *image,char* colors){
    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                                                 bitsPerComponent, bytesPerRow, colorSpace,
                                                 kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    for (int x=0; x<width; x++) {
        for (int y=0; y<height; y++) {
            int idx=width*y+x;
            int byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
            colors[idx*4]=rawData[byteIndex];
            colors[idx*4+1]=rawData[byteIndex+1];
            colors[idx*4+2]=rawData[byteIndex+2];
            colors[idx*4+3]=rawData[byteIndex+3];
        }
    }
    free(rawData);
    return width*height*4;
}

@implementation UIImage (utils)

+(UIImage*)imageWithSize:(CGSize)size{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+(UIImage*)imageWithString:(NSString*)string font:(UIFont*)font{
    if (font==nil) {
        font=[UIFont systemFontOfSize:32];
    }
    UILabel *label=[[UILabel alloc] initWithFrame:CGRectZero];
    label.text=string;
    label.font=font;
    label.numberOfLines=0;
    [label sizeToFit];
    CGRect canvas=CGRectMake(0, 0, CGRectGetWidth(label.bounds)+10, CGRectGetHeight(label.bounds)+10);
    CGRect layer=CGRectMake(5, 5, CGRectGetWidth(label.bounds), CGRectGetHeight(label.bounds));
    UIGraphicsBeginImageContext(canvas.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:0.0 alpha:0.5].CGColor);
    CGContextFillRect(context, canvas);
    CGContextSetFillColorWithColor(context, [UIColor colorWithWhite:1.0 alpha:1.0].CGColor);
    [string drawInRect:layer withFont:font];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


- (UIImage *)imageMaskedWithImage:(UIImage *)maskImage{
	CGImageRef maskImageRef = CGImageMaskCreate(CGImageGetWidth(maskImage.CGImage),
                                                CGImageGetHeight(maskImage.CGImage),
                                                CGImageGetBitsPerComponent(maskImage.CGImage),
                                                CGImageGetBitsPerPixel(maskImage.CGImage),
                                                CGImageGetBytesPerRow(maskImage.CGImage),
                                                CGImageGetDataProvider(maskImage.CGImage),
                                                NULL,
                                                false);
	CGImageRef maskedImageRef = CGImageCreateWithMask(self.CGImage, maskImageRef);
    CGImageRelease(maskImageRef);
	UIImage *maskedImage = [UIImage imageWithCGImage:maskedImageRef];
    CGImageRelease(maskedImageRef);
    return maskedImage;
}


-(UIImage*)resizeImage:(CGSize)size mode:(ImageResizeMode)mode{
    float scale=1;
    switch (mode) {
        case ImageResizeModeAspectFill:
            scale=MAX(size.width/self.size.width, size.height/self.size.height);
            break;
        case ImageResizeModeAspectFit:
            scale=MIN(size.width/self.size.width, size.height/self.size.height);
            break;
        case ImageResizeModeExpand:
            scale=MAX(size.width/self.size.width, size.height/self.size.height);
            size=CGSizeMake(self.size.width*scale, self.size.height*scale);
            break;
        default://ImageResizeModeCenter
            scale=MIN(size.width/self.size.width, size.height/self.size.height);
            scale=MIN(1, scale);
            break;
    }
    CGRect rect=CGRectMake((size.width-self.size.width*scale)/2, (size.height-self.size.height*scale)/2, self.size.width*scale, self.size.height*scale);
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(ctx, YES);
    CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
    [self drawInRect:rect];
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

-(UIImage*)resizeImage:(CGSize)size{
    return [self resizeImage:size mode:ImageResizeModeExpand];
}

-(UIImage*)cropImage:(CGRect)rect{
    if (CGRectIntersectsRect(rect, CGRectMake(0, 0, self.size.width, self.size.height))) {
        CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
        UIImage *result = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
        return result;
    }else{
        return nil;
    }
}

-(UIImage*)rotateImage:(CGFloat)degrees{
    // calculate the size of the rotated view's containing box for our drawing space
    CGRect frameRect=CGRectMake(0,0,self.size.width, self.size.height);
    CGAffineTransform transform=CGAffineTransformMakeRotation(D2R(degrees));
    frameRect=CGRectApplyAffineTransform(frameRect, transform);
    CGSize rotatedSize = frameRect.size;
    // Create the bitmap context
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();
    // Move the origin to the middle of the image so we will rotate and scale around the center.
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    // Rotate the image context
    CGContextRotateCTM(bitmap, D2R(degrees));
    // Now, draw the rotated/scaled image into the context
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2, self.size.width, self.size.height), [self CGImage]);
    // Create image
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;}

-(UIImage*)tintColor:(UIColor *)color{
    color=[color colorWithAlphaComponent:0.5];
    CGRect rect=CGRectMake(0, 0, self.size.width, self.size.height);
    UIGraphicsBeginImageContext(self.size);
    CGContextRef ctx=UIGraphicsGetCurrentContext();
    CGContextSetAllowsAntialiasing(ctx, YES);
    CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
    CGContextSetFillColorWithColor(ctx, color.CGColor);
    CGContextFillRect(ctx, rect);
    [self drawInRect:rect blendMode:kCGBlendModeOverlay alpha:1.0];
    UIImage* result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

-(UIImage*)trimImage{
    //TODO:trimImage
    return self;
}

-(UIColor*)colorAtPoint:(CGPoint)point{
    UIColor *color = nil;
    if (CGRectContainsPoint(CGRectMake(0, 0, self.size.width, self.size.height), point)) {
        int indexofpixel=(point.y*self.size.width)+point.x;
        int numofpixel=self.size.width*self.size.height;
        char *rgba8data=malloc(numofpixel*sizeof(char)*4);
        memset(rgba8data, 0, numofpixel*sizeof(char)*4);
        rgba8FromImage(self,rgba8data);
        indexofpixel=MIN(numofpixel-1, indexofpixel);
        indexofpixel=MAX(0, indexofpixel);
        char red=rgba8data[indexofpixel*4];
        char green=rgba8data[indexofpixel*4+1];
        char blue=rgba8data[indexofpixel*4+2];
        char alpha=rgba8data[indexofpixel*4+3];
        color=[UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha/255.0];
        free(rgba8data);
    }
    return color;
}

@end

UIImage* UIImageObj(NSData *data){
    return [UIImage imageWithData:data];
}

UIImage* BitmapString(NSString *str){
    NSDictionary *dict=[NSDictionary dictionaryWithContentsOfFile:@"sprite_512.plist".mediaPath];
    UIImage *image=[UIImage imageWithContentsOfFile:@"sprite_512.png".mediaPath];
    NSDictionary *sheet=dict[@"frames"];
    NSRange range;
    UIView *canvas=[[UIView alloc] initWithFrame:CGRectZero];
    int x=0;
    for (int i=0; i<str.length; i++) {
        range=NSMakeRange(i, 1);
        NSString *c=[str substringWithRange:range];
        NSDictionary *sprite=sheet[c];
        NSString *frame=sprite[@"textureRect"];
        CGRect texture=CGRectFromString(frame);
        UIImage *ci=[image cropImage:texture];
        UIImageView *cv=[[UIImageView alloc] initWithImage:ci];
        [canvas addSubview:cv];
        cv.frame=CGRectMake(x, 0, texture.size.width, texture.size.height);
        x=x+texture.size.width;
    }
    [canvas sizeToAuto];
    return [canvas imageFromView];
}
